package com.android.bandroid.api.service.impl;

import android.app.Application;
import android.content.Context;

import com.android.bandroid.api.model.ApiResponse;
import com.android.bandroid.api.service.Api;
import com.android.bandroid.api.util.CoreCallbackListener;
import com.android.bandroid.api.util.JsonUtil;
import com.android.bandroid.api.util.MD5Util;
import com.android.bandroid.api.util.VolleySingleton;
import com.android.bandroid.model.LoginResp;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectParamsRequest;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Kevin on 2015/11/3.
 */
public class ApiImpl extends Application implements Api{
    //volley对象
    private VolleySingleton mVolleySingleton = null;
    private static final String APP_SUCCESS = "app_0";     //  APP成功编码
    private static final String APP_FAILED = "app_1";     //  APP失败编码
    private static final String API_SUCCESS = "Y";     //  APP成功编码

    public ApiImpl(Context context) {
        this.mVolleySingleton = VolleySingleton.getVolleySingleton(context);
    }

    /**
     * 登录
     * @param userName 用户名
     * @param password  MD5加密的密码
     * @return
     */
    @Override
    public void loginByApp(final String userName, final String password, final CoreCallbackListener<ApiResponse<LoginResp>> listener) {
        final ApiResponse<LoginResp> apiResponse = new ApiResponse<LoginResp>();      //  返回对象
        Map<String, String> params = new HashMap<String, String>();
        params.put("userName", userName);
        params.put("password", MD5Util.getMD5String(password));
        JsonObjectParamsRequest jsonObjectRequest = new JsonObjectParamsRequest(Api.LOGIN_BY_APP, params,
                new Response.Listener<JSONObject>(){
                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        LoginResp loginResp = JsonUtil.toBean(jsonObject.toString(), LoginResp.class);
                        if(API_SUCCESS.equals(loginResp.getSuccessFlag())){     //  后台返回成功
                            apiResponse.setCode(APP_SUCCESS);
                            apiResponse.setObj(loginResp);
                            listener.onSuccess(apiResponse);
                        }else{
                            listener.onFailure("1", loginResp.getErrorMsg());
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        listener.onFailure("1", volleyError.getMessage());
                    }
                });
        mVolleySingleton.addToRequestQueue(jsonObjectRequest);
    }
}
